package com.daxilong.starchen.player.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.audiofx.Visualizer;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.view.View;
import android.widget.SeekBar;
import android.widget.Toast;

import com.daxilong.starchen.player.IMediaService;
import com.daxilong.starchen.player.R;
import com.daxilong.starchen.player.databinding.ActivityAudioPlayerBinding;
import com.daxilong.starchen.player.model.MediaItem;
import com.daxilong.starchen.player.service.MediaService;
import com.daxilong.starchen.player.utils.LyricUtils;
import com.daxilong.starchen.player.utils.Utils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;

public class AudioPlayerActivity extends BaseActivity {

    private static final int PROGRESS = 1;
    //显示歌词-歌词缓缓往上推移
    private static final int SHOW_LYRIC = 2;
    //音频播放的列表位置
    private int position;

    //MediaService的代理类
    private IMediaService mediaService;

    private ActivityAudioPlayerBinding binding;

    /**
     * 判断从哪里来
     * true: 屏幕快捷状态栏点击来的
     * false:从列表点击来的
     */
    private boolean notification = false;
    private Visualizer mVisualizer;

    private final Handler handler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case SHOW_LYRIC://显示歌词-缓缓往上推移
                    try {
                        int currentPosition = mediaService.getCurrentPosition();
                        binding.lyricShowview.setShowNextLyric(currentPosition);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    removeMessages(SHOW_LYRIC);
                    sendEmptyMessage(SHOW_LYRIC);
                    break;
                case PROGRESS://更新时间
                    //得到当前的进度
                    try {
                        int currentPosition = mediaService.getCurrentPosition();
                        int duration = mediaService.getDuration();

                        binding.tvTime.setText(Utils.stringForTime(currentPosition)+"/"+Utils.stringForTime(duration));
                        //跟新进度
                        binding.seekbarAudio.setProgress(currentPosition);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }

                    handler.removeMessages(PROGRESS);
                    handler.sendEmptyMessageDelayed(PROGRESS,1000);
                    break;
            }
        }
    };

    @Override
    protected View getLayout() {
        binding = ActivityAudioPlayerBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }

    @Override
    public void initView(){
        //开始暂停
        binding.btnAudioStartPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if(mediaService.isPlaying()){
                        //暂停
                        mediaService.pause();
                        //按钮设置播放状态
                        binding.btnAudioStartPause.setBackgroundResource(R.drawable.btn_audio_start_selector);
                    }else{
                        //播放
                        mediaService.start();
                        //按钮设置暂停状态
                        binding.btnAudioStartPause.setBackgroundResource(R.drawable.btn_audio_pause_selector);
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });
        //进度条
        binding.seekbarAudio.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(fromUser){
                    try {
                        mediaService.seekTo(progress);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        //播放模式 顺序 循环
        binding.btnAudioPlaymode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changePlaymode();
            }
        });
        //上一个
        binding.btnAudioPre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mediaService.pre();
                } catch (RemoteException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        //下一个
        binding.btnAudioNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mediaService.next();
                } catch (RemoteException e) {
                    throw new RuntimeException(e);
                }
            }
        });

    }

    @Override
    public void initData() {
        notification = getIntent().getBooleanExtra("Notification",false);
        position = getIntent().getIntExtra("position", 0);

        bindAndStartService();
        EventBus.getDefault().register(this);
    }

    private void bindAndStartService() {
        Intent intent = new Intent(this, MediaService.class);
        intent.setAction("com.daxilong.audio.OPENAUDIO");
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
        startService(intent);
    }

    @Subscribe
    public void onEventMainThread(MediaItem mediaItem) {
        //获取视频的名称和演唱者的信息--
        setAudioData();
        try {
            binding.seekbarAudio.setMax(mediaService.getDuration());
        } catch (RemoteException e) {
            e.printStackTrace();
        }

        handler.sendEmptyMessage(PROGRESS);

        setPlayAndpauseState();
        showLyric();
        setupVisualizerFxAndUi();
    }

    /**
     * 设置歌曲名称和演唱者
     */
    private void setAudioData() {
        try {
            binding.tvName.setText(mediaService.getName());
            binding.tvArtist.setText(mediaService.getArtist());
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成一个VisualizerView对象，使音频频谱的波段能够反映到 VisualizerView上
     */
    private void setupVisualizerFxAndUi() {
        try {
            int audioSessionid = mediaService.getAudioSessionId();
            mVisualizer = new Visualizer(audioSessionid);
            // 参数内必须是2的位数
            mVisualizer.setCaptureSize(Visualizer.getCaptureSizeRange()[1]);
            // 设置允许波形表示，并且捕获它
            binding.baseVisualView.setVisualizer(mVisualizer);
            mVisualizer.setEnabled(true);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private void showLyric() {
        LyricUtils lyricUtils = new LyricUtils();
        try {
            String path =  mediaService.getAudioPath();//mnt/sdcard/audio/beijing.mp3
            path = path.substring(0,path.indexOf("."));////mnt/sdcard/audio/beijing;

            File file = new File(path+".lrc");//////mnt/sdcard/audio/beijing.lrc
            if(!file.exists()){
                file = new File(path+".txt");//////mnt/sdcard/audio/beijing.txt
            }

            lyricUtils.readLyricFile(file);//传文件进入解析歌词工具类

            //把解析好的歌词传入显示歌词的控件上
            binding.lyricShowview.setLyrics(lyricUtils.getLyrics());
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        if(lyricUtils.isExistLyric()){
            handler.sendEmptyMessage(SHOW_LYRIC);
        }
    }

    private void changePlaymode() {
        try {
            int playmode = mediaService.getPlaymode();

            if (playmode == MediaService.ORDER_PLAY) {
                playmode = MediaService.REPEAT_SINGLE;
            } else if (playmode == MediaService.REPEAT_SINGLE) {
                playmode = MediaService.REPEAT_ALL;
            } else if (playmode == MediaService.REPEAT_ALL) {
                playmode = MediaService.ORDER_PLAY;
            }
            //保持到Service的实例中
            mediaService.setPlaymode(playmode);
            showPlaymode();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private void showPlaymode() {
        try {
            int playmode = mediaService.getPlaymode();//从服务里面

            if (playmode == MediaService.ORDER_PLAY) {
                Toast.makeText(AudioPlayerActivity.this, "顺序播放", Toast.LENGTH_SHORT).show();
                binding.btnAudioPlaymode.setBackgroundResource(R.drawable.btn_audio_playmode_normal_selector);
            } else if (playmode == MediaService.REPEAT_SINGLE) {
                Toast.makeText(AudioPlayerActivity.this, "单曲播放", Toast.LENGTH_SHORT).show();
                binding.btnAudioPlaymode.setBackgroundResource(R.drawable.btn_audio_playmode_single_selector);
            } else if (playmode == MediaService.REPEAT_ALL) {
                Toast.makeText(AudioPlayerActivity.this, "全部播放", Toast.LENGTH_SHORT).show();
                binding.btnAudioPlaymode.setBackgroundResource(R.drawable.btn_audio_playmode_all_selector);
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private void setPlayAndpauseState() {
        try {
            if(mediaService !=null){
                if(mediaService.isPlaying()){
                    //暂停状态
                    binding.btnAudioStartPause.setBackgroundResource(R.drawable.btn_audio_pause_selector);
                }else{
                    //播放状态
                    binding.btnAudioStartPause.setBackgroundResource(R.drawable.btn_audio_start_selector);
                }
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mediaService = IMediaService.Stub.asInterface(service);
            try {
                if(!notification){
                    mediaService.openAudio(position);
                }else{
                    //获取数据-要服务发广播
                    mediaService.notifyChange(MediaService.OPEN_AUDIO);
                }

            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        /**
         * 当Activity和服务断开的时候回调这个方法
         * @param name
         */
        @Override
        public void onServiceDisconnected(ComponentName name) {
            mediaService = null;
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if(conn != null){
            unbindService(conn);
            conn = null;
        }
    }

}